<template>
  <div class="container">
    <!-- 导航固定定位 fixed -->
    <van-nav-bar fixed title="搜索结果" left-arrow @click-left="$router.back()" />
    <!-- 文章列表 -->
    <van-pull-refresh :success-text="refreshTxt" v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="onLoad" finished-text="没有更多了">
        <van-cell v-for="item in list" :key="item.art_id.toString()" :to="`/article/${item.art_id.toString()}`">
          <div class="article_item">
            <h3 class="van-ellipsis">
              PullRefresh下拉刷新PullRefresh下拉刷新下拉刷新下拉刷新
            </h3>
            <div class="img_box" v-if="item.cover.images.length">
              <van-image lazy-load v-for="(img,i) in item.cover.images" :key="i" :class="item.cover.type===1?'w100':'w33'" fit="cover" :src="img" />
            </div>
            <div class="info_box">
              <span>{{item.aut_name}}</span>
              <span>{{item.comm_count}}评论</span>
              <span>{{item.pubdate|relTime}}</span>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { searchArticles } from '@/api/article' // 引入获取搜索结果列表
export default {
  name: 'search-result',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      // 是否正在刷新
      refreshing: false,
      refreshTxt: ''
    }
  },
  created () {
    // console.log(this.$route.query.q)
    this.query = {
      page: 1,
      q: this.$route.query.q
    }
  },
  methods: {
    async onLoad () {
      try {
        // 异步更新数据
        const { status, data } = await searchArticles(this.query)
        // console.log(data)
        if (status === 200) {
          // 追加列表数据
          this.list.push(...data.results)
          // 加载状态结束
          this.loading = false
          // 刷新完成
          this.refreshing = false
          this.refreshTxt = '刷新成功'
          // 数据全部加载完成
          if (data.pre_timestamp) {
            this.timestamp = data.pre_timestamp
          } else {
            this.finished = true
          }
        }
      } catch (error) {

      }
    },
    // 下拉刷新执行
    onRefresh () {
      // 清空列表数据
      if (this.refreshing) {
        this.list = []
      }
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.finished = false
      this.loading = true
      // 设置最新的时间戳
      this.timestamp = Date.now()
      this.onLoad()
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding-top: 46px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}
.article_item {
  h3 {
    font-weight: normal;
    line-height: 2;
  }
  .img_box {
    display: flex;
    justify-content: space-between;
    .w33 {
      width: 33%;
      height: 90px;
    }
    .w100 {
      height: 180px;
      width: 100%;
    }
  }
  .info_box {
    color: #999;
    line-height: 2;
    position: relative;
    span {
      padding-right: 10px;
    }
  }
}
</style>
